package com.lgx.authorize.module.service.impl;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.lgx.authorize.module.dao.IAuthorizeUserInfoDao;
import com.lgx.authorize.module.entity.ApplicationApplykeyInfo;
import com.lgx.authorize.module.entity.AuthorizeUserInfo;
import com.lgx.authorize.module.service.IAuthorizeUserInfoService;
import com.lgx.right.entity.User;

@Service("authorizeUserInfoService")
public class AuthorizeUserInfoService implements IAuthorizeUserInfoService {

	@Autowired
	IAuthorizeUserInfoDao authorizeUserInfoDao;
	
	@Override
	public void createAuthorizeUserInfo(AuthorizeUserInfo authorizeUserInfo) {
		authorizeUserInfoDao.createAuthorizeUserInfo(authorizeUserInfo);
	}

	@Override
	public void updateAuthorizeUserInfo(AuthorizeUserInfo authorizeUserInfo) {
		authorizeUserInfoDao.updateAuthorizeUserInfo(authorizeUserInfo);
	}

	@Override
	public void deleteAuthorizeUserInfo(AuthorizeUserInfo authorizeUserInfo) {
		authorizeUserInfoDao.deleteAuthorizeUserInfo(authorizeUserInfo);
	}

	@Override
	public AuthorizeUserInfo findAuthorizeUserInfoById(int systemid) {
		return authorizeUserInfoDao.findAuthorizeUserInfoById(systemid);
	}

	@Override
	public AuthorizeUserInfo findAuthorizeUserInfoByUser(User user) {
		return authorizeUserInfoDao.findAuthorizeUserInfoByUser(String.valueOf(user.getId()));
	}

	@Override
	public List<AuthorizeUserInfo> listAllAuthorizeUserInfos() {
		return authorizeUserInfoDao.listAllAuthorizeUserInfos();
	}

	@Override
	public AuthorizeUserInfo authorizeUserForApplication(User user,
			ApplicationApplykeyInfo applicationApplykeyInfo) {
		AuthorizeUserInfo info = new AuthorizeUserInfo();
		String token = genToken(user);
		info.setStartTime(new Date());
		info.setUserId(String.valueOf(user.getId()));
		info.setAppkeyId(applicationApplykeyInfo.getSystemid());
		info.setAuthorizeToken(token);
		info.setEndTime(applicationApplykeyInfo.getDisableTime());
		authorizeUserInfoDao.createAuthorizeUserInfo(info);
		return info;
	}
	
	/**
	 * token create rule
	 * @param user
	 * @return
	 */
	private String genToken(User user){
		Date date = new Date();
		String hash = String.valueOf(user.hashCode());
		return date.getTime()+hash;
	}

	@Override
	public List<AuthorizeUserInfo> listAllAuthorizeUserInfosFromApplication(
			ApplicationApplykeyInfo applicationApplykeyInfo) {
		return authorizeUserInfoDao.listAuthorizeUserInfosByAppKey(applicationApplykeyInfo);
	}
	
}
